function h = createEEGFigure(x, y, spindles, plotTitles, titleText, filtered)

% validate arguments
failIfFalse(isvector(x), 'x should be a vector');

failIfFalse(iscell(spindles), 'spindles should be a cell array');
failIfFalse(iscellstr(plotTitles), 'plotTitles should be a string cell array');

failIfFalse(ischar(titleText), 'titleText should be a string');

failIfFalse(islogical(filtered), 'filtered should be a logical array');


failIfFalse(size(y, 2) == size(plotTitles, 2), ...
            'Number of plots and plot titles is not the same');

failIfFalse(size(y, 2) == size(spindles, 2), ...
            'Number of plots and spindle plots is not the same');


failIfFalse(size(plotTitles, 2) == size(spindles, 2),...
    'Number of plot titles and spindle plots is not the same');

    
n = size(y, 2);
failIfFalse(n <= 3, 'not more than 3 plots per figure are allowed');

% create the plots
counter = 0;
for k = y
    counter = counter + 1;
    makeAxes(x, k, spindles{counter}, plotTitles{counter}, counter, n, filtered(counter));
end

setTitle(titleText);
 
set(gcf, 'Visible', 'off');

h = gcf;

%--------------------------------------------------------------------------
function ax = makeAxes(x, y, spindles, plotTitle, position, nplots, filtered)

% axes limits
xTick = 0:1:16;
xLim = [0 16];
minorTick = 0:0.125:16;

if(~filtered)
	yTick = -140:35:140;
	yLim = [-140 140];
else
	yTick = -60:30:60;
	yLim = [-60 60];
end


% ax1
axes('XTick', xTick, 'YTick', [], 'TickDir', 'out', 'FontSize', 10, ...
           'XLim', xLim, 'YLim', yLim);
xlabel('seconds', 'VerticalAlignment', 'top');
setAxesPosition(@gca, position, nplots);


% ax2
ax2 = axes('XTick', minorTick, 'XTickLabel', [], 'YTick', yTick,...
           'TickDir', 'out', 'FontSize', 10, ...
           'XLim', xLim, 'YLim', yLim);
ylabel('Voltage amplitude (\muV)');
title(plotTitle);

line(x, y, 'LineWidth', 0.5, 'Parent', ax2);
set(gca, 'GridLineStyle', ':');
set(gca,'XGrid','on');
set(gca, 'LineWidth', 0.4);

%spindles
minY = min(y) - 7;
maxY = max(y) + 7;

nrows = size(spindles, 1);
for i = 1:nrows
    row = spindles(i, :);
    spindle = row';
    minX = spindle(1);
    maxX = spindle(length(spindle));
    rectangle('Position', [minX, minY, maxX - minX, maxY - minY], 'LineWidth', 0.7, 'EdgeColor', 'red');
end

setAxesPosition(@gca, position, nplots);

ax = gca;

%--------------------------------------------------------------------------



















